package manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import manage.dao.RatesMapper;
import manage.model.Rates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RatesServiceImpl {
    @Autowired
    private RatesMapper ratesMapper;

    public PageInfo<Rates> selectAll(String page, String limit) {
        int pu = Integer.parseInt(page);
        int li = Integer.parseInt(limit);
        PageHelper.startPage(pu,li);
        List<Rates> list = ratesMapper.selectAll();
        PageInfo<Rates> pageInfo = new PageInfo<Rates>(list);
        return pageInfo;
    }

    public String insert(Rates record) {
        int i = ratesMapper.insert(record);
        if(i>0)
            return "success";
        return "fail";
    }
    public String del(Integer id) {
        int i = ratesMapper.deleteByPrimaryKey(id);
        if(i>0)
            return "success";
        return "fail";
    }
    public Rates select(Integer id) {
        return ratesMapper.selectByPrimaryKey(id);
    }
    public String update(Rates record){
        if(ratesMapper.updateByPrimaryKey(record)>0)
            return "success";
        return "fail";
    }
    public Integer getMoney(Integer money){
        int m = money;
        List<Rates> list = ratesMapper.selectAll();
        Map<Integer,Rates> map=new HashMap<Integer,Rates>();
        int level = 0;
        for (int i = 0; i <list.size() ; i++) {
            int start = list.get(i).getStart();
            int end =list.get(i).getEnd();
            int level1 = list.get(i).getLevel();
            map.put(level1,list.get(i));
            if(end==-1){
                if (money> start){
                    level = list.get(i).getLevel();
                }
            }else{
                if (money> start && money<=end){
                    level = list.get(i).getLevel();
                }
            }
        }
        int mon = 0;

        while (true) {
            if(level==0){
                break;
            }
            Rates rates = map.get(level);
            level--;
            mon += (money-rates.getStart())*rates.getPer()/100 ;
            money=money-rates.getStart();
        }
        return m-mon;
    }
}
